package com.wins.bbs.auth;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

public class AuthError implements AuthenticationEntryPoint, AccessDeniedHandler {

    @Override
    public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {
        handleAccessDenied(request, response, authException);
    }

    private static void handleAccessDenied(final HttpServletRequest request, final HttpServletResponse response, final Exception exception) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        String message = "authentication error: ";
        if (exception.getCause() != null) {
            message += exception
                    .getCause()
                    .getMessage();
        } else {
            message += exception.getMessage();
        }
        final byte[] body = message.getBytes();
        response
                .getOutputStream()
                .write(body);

    }

    @Override
    public void handle(final HttpServletRequest request, final HttpServletResponse response, final AccessDeniedException accessDeniedException) throws IOException, ServletException {
        handleAccessDenied(request, response, accessDeniedException);
    }

}